package com.yjw.demo.mybatis.common.exception;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yjw.demo.mybatis.common.pojo.DataResponse;

/**
 * 全局异常处理
 * 
 * @author yinjianwei
 * @date 2018/07/30
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 拦截捕捉业务异常
     * 
     * @param ex
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public DataResponse myErrorHandler(ServiceException e, HttpServletRequest request) {
        String userIp = request.getRemoteAddr();
        String requestURL = request.getRequestURL().toString();
        String params = request.getQueryString();
        Date date = new Date();
        logger.error(String.format("Service Exception Log, time: %tF %tT|userIp: %s|requestURL: %s|params: %s", date,
            date, userIp, requestURL, params), e);
        return DataResponse.error(e.getErrorCode(), e.getMessage());
    }

    /**
     * 全局异常捕捉处理
     * 
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public DataResponse errorHandler(Exception e, HttpServletRequest request) {
        String userIp = request.getRemoteAddr();
        String requestURL = request.getRequestURL().toString();
        String params = request.getQueryString();
        Date date = new Date();
        logger.error(String.format("Exception Log, time:%tF %tT|userIp:%s|requestURL:%s|params:%s", date, date, userIp,
            requestURL, params), e);
        return DataResponse.error();
    }

}
